<?php
/**
 * Smithy PHP library
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * Smithy is a free Zend Framework based PHP library.
 *
 * @category   Smithy
 * @package    Smithy_Model
 * @subpackage Value
 * @copyright  Copyright (c) 2008-2009 Kovács Tamás
 * @license    New BSD License
 * @version    $Id: Abstract.php ktamas $
 */

/**
 * @see Zend_Form_Element_Hidden
 */
require_once ('Zend/Form/Element/Hidden.php');
/**
 * @see Zend_Form_Element_Xhtml
 */
require_once ('Zend/Form/Element/Xhtml.php');
/**
 * @see Zend_Form_Element
 */
require_once ('Zend/Form/Element.php');
/**
 * @see Zend_Validate_Interface
 */
require_once ('Zend/Validate/Interface.php');

/**
 * Security token field for forms.
 *
 * @author Kovács Tamás
 * @category Smithy
 * @package Smithy_Form
 * @subpackage Element
 */
class Smithy_Form_Element_Token extends Zend_Form_Element_Hidden
{
    /**
     * Initialize Element
     *
     * @see Zend_Form_Element_Hidden::init()
     * @return void
     */
    public function init()
    {
        parent::init();
        $this->setRequired();
    }

    /**
     * Clears the element's decorators.
     *
     * @see Zend_Form_Element_Hidden::render()
     */
    public function render($view = null)
    {
        $this->clearDecorators()
            ->setDecorators(array(
                'ViewHelper')
            );

        $this->_generateTokenValue();
        return parent::render($view);
    }

    /**
     * Checks form token and validate element value.
     *
     * @see Zend_Form_Element_Hidden::isValid()
     * @param mixed $value
     * @param mixed $context [OPTIONAL]
     * @return bool
     */
    public function isValid($value, $context = null)
    {
        $session = new Zend_Session_Namespace(__CLASS__);
        if (!isset($session->SmithyFormElementToken)) {
            $this->addError('Form token does not exists. ');
            return false;
        }
        if ((string)$value !== (string)$session->SmithyFormElementToken) {
            $this->addError('Invalid form token. ');
            return false;
        }
        return parent::isValid($value, $context);
    }

    /**
     * Generates token value, and saves it into the value attribute.
     *
     * @return void
     */
    protected function _generateTokenValue()
    {
        $this->setValue(
            md5(mktime() . rand(10000, 100000))
        );
        $session = new Zend_Session_Namespace(__CLASS__);
        $session->SmithyFormElementToken = $this->getValue();
    }
}
